/**
 * 
 */
package com.iwords.api.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.constants.Constants;
import com.iwords.enums.KnownLevel;
import com.iwords.service.LearningStatusServiceLocal;
import com.iwords.service.UserServiceLocal;
import com.iwords.service.WordServiceLocal;
import com.iwords.service.object.LearningStatusEntity;
import com.iwords.service.object.SysLibWordsEntity;
import com.iwords.service.object.UserEntity;
import com.iwords.utils.CodeUtils;
import com.iwords.utils.StringUtils;
import com.iwords.api.web.base.BaseAction;

/**
 * @author       BOLIN.HBC 
 * @time         2011-4-5    
 * @description  用户学习状态-SERVLET       
 */
@WebServlet(name = "learningStatusAction", urlPatterns = {"/learningStatus"})
public class LearningStatusAction extends BaseAction<LearningStatusEntity> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @EJB
    private LearningStatusServiceLocal learningStatusService;
    @EJB
    private WordServiceLocal wordService;
    @EJB
    private UserServiceLocal userService;

    public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
        String action = req.getParameter("action");
        if (Constants.LEARNINGSTATUS_MOVE_SYSLIB.equals(action)) {
            doMoveSysLib(req, res);
        } else if (Constants.LEARNINGSTATUS_CHANGE_WORDSTATUS.equals(action)) {
            doChangeStatus(req, res);
        } else if (Constants.LEARNINGSTATUS_LIST.equals(action)) {
            doGetStatusList(req, res);
        } else if (Constants.FINAL_LEARNING_STATUS.equals(action)) {
            doGetFinalList(req, res);
        } else if (Constants.LEARNINGSTATUS_GETALL_NUMBER.equals(action)) {
            doFindAllLearningNumber(req, res);
        } else if (Constants.LEARNINGSTATUS_GETWORD_BY_LEVEL.equals(action)) {
            doFindWordsByLevel(req, res);
        }
    }

    public void doGetFinalList(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        LearningStatusEntity entity = initEntity(req);

        entity.setFamiliarity(KnownLevel.Known.getValue());
        jsonPrint(res, getJson(learningStatusService.getFinalList(entity)));
    }

    private void doFindAllLearningNumber(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        JSONObject result = new JSONObject();
        LearningStatusEntity entity = initEntity(req);
        try {
            JSONObject defaultValue = new JSONObject(learningStatusService.findAllLearningNumber(entity));
            result.put(Constants.DEFAULT_VALUE, defaultValue);
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        } catch (Exception e) {
            log.error("获取当前课本状态数字出错", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
        }
        jsonPrint(res, result);

    }

    private void doFindWordsByLevel(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        LearningStatusEntity entity = initEntity(req);
        com.iwords.utils.JSONObject defaultValue = new com.iwords.utils.JSONObject();
        try {
            List<LearningStatusEntity> resultList = learningStatusService.getLevelList(entity);

            defaultValue.putColumn("id", "libid", "wordid", "spelling", "meaning", "phonetics", "userid", "updatetime", "familiarity");
            for (LearningStatusEntity en : resultList) {

                defaultValue.putValue(en.getId(), en.getLibid(), en.getWord().getWordid(), CodeUtils.encode(en.getWord().getSpelling()), CodeUtils.encode(en.getWord().getMeaning()), CodeUtils.encode(en.getWord().getPhonetics()), en.getUserid(), en.getUpdatetime() != null ? en.getUpdatetime().getTime() : 0L, en.getFamiliarity());

            }
        } catch (Exception e) {
            log.error("获取用户状态列表失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
        }
        result.put(Constants.DEFAULT_VALUE, defaultValue);
        jsonPrint(res, result);
    }

    private JSONObject getJson(List<LearningStatusEntity> resultList) throws JSONException {
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        try {

            com.iwords.utils.JSONObject defaultValue = new com.iwords.utils.JSONObject();
            defaultValue.putColumn("id", "libid", "wordid", "spelling", "meaning", "phonetics", "userid", "updatetime", "familiarity");
            for (LearningStatusEntity en : resultList) {

                defaultValue.putValue(en.getId(), en.getLibid(), en.getWord().getWordid(), CodeUtils.encode(en.getWord().getSpelling()), CodeUtils.encode(en.getWord().getMeaning()),
                        CodeUtils.encode(en.getWord().getPhonetics()), en.getUserid(), en.getUpdatetime() != null ? en.getUpdatetime().getTime() : 0L,
                        en.getFamiliarity());

            }
            result.put(Constants.DEFAULT_VALUE, defaultValue);
        } catch (Exception e) {
            log.error("获取用户学习状态列表失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
        }
        return result;

    }

    private JSONObject getJson(List<LearningStatusEntity> resultList, Long libid) throws JSONException {
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        try {

            List<SysLibWordsEntity> wordList = wordService.findWordsBySysLibId(libid);
            Map<Long, SysLibWordsEntity> map = new HashMap<Long, SysLibWordsEntity>();
            for (SysLibWordsEntity en : wordList) {
                map.put(en.getWordid(), en);
            }

            com.iwords.utils.JSONObject defaultValue = new com.iwords.utils.JSONObject();
            defaultValue.putColumn("id", "libid", "wordid", "spelling", "meaning", "phonetics", "userid", "updatetime", "familiarity");
            for (LearningStatusEntity en : resultList) {
                SysLibWordsEntity e = map.get(en.getWord().getWordid());
                if (e == null) {
                    defaultValue.putValue(en.getId(), en.getLibid(), en.getWord().getWordid(), "", "", "", en.getUserid(), en.getUpdatetime() != null ? en.getUpdatetime().getTime() : 0L, en.getFamiliarity());
                } else {
                    defaultValue.putValue(en.getId(), en.getLibid(), en.getWord().getWordid(), CodeUtils.encode(e.getSpelling()), CodeUtils.encode(e.getMeaning()),
                            CodeUtils.encode(e.getPhonetics()), en.getUserid(), en.getUpdatetime() != null ? en.getUpdatetime().getTime() : 0L,
                            en.getFamiliarity());
                }
            }
            result.put(Constants.DEFAULT_VALUE, defaultValue);
        } catch (Exception e) {
            log.error("获取用户学习状态列表失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
        }
        return result;

    }

    public void doGetStatusList(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        LearningStatusEntity entity = initEntity(req);
        List<LearningStatusEntity> resultList = learningStatusService.getStatusList(entity);
        jsonPrint(res, getJson(resultList, entity.getLibid()));

    }

    public void doChangeStatus(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        LearningStatusEntity entity = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);

        try {
            learningStatusService.changeStatus(entity);
        } catch (Exception e) {
            log.error("修改用户学习状态失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
        }
        jsonPrint(res, result);

    }

    public void doMoveSysLib(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        LearningStatusEntity entity = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        try {
            if (learningStatusService.moveSysLib(entity)) {
                result.put(Constants.DEFAULT_VALUE, true);
            }

        } catch (Exception e) {
            log.error("用户选择课本失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
        }
        jsonPrint(res, result);
    }

    public LearningStatusEntity initEntity(HttpServletRequest req) {
        LearningStatusEntity entity = new LearningStatusEntity();
        String userid = req.getParameter("userid");

        if (StringUtils.isNotBlank(userid)) {
            entity.setUserid(Long.parseLong(userid));
        }
        String wordid = req.getParameter("wordid");
        if (StringUtils.isNotBlank(wordid)) {
            SysLibWordsEntity word = new SysLibWordsEntity();
            word.setWordid(Long.parseLong(wordid));
            entity.setWord(word);
        }
        String libid = req.getParameter("libid");
        if (StringUtils.isNotBlank(libid)) {

            entity.setLibid(Long.parseLong(libid));
        }
        String familiarity = req.getParameter("familiarity");
        if (StringUtils.isNotBlank(familiarity)) {

            entity.setFamiliarity(Integer.parseInt(familiarity));
        } else {
            entity.setFamiliarity(0);

        }
        return entity;
    }
}
